#include "gamewindow.h"
#include "ui_gamewindow.h"
#include"config.h"
#include<QWidget>
#include<QTimer>
#include<QPainter>
#include<QKeyEvent>
GameWindow::GameWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::GameWindow)
{
    ui->setupUi(this);
    initScene();
    playGame();
    mPlaneMoveTimer=new QTimer(this);
    mPlaneMoveTimer->start(30);
    connect(mPlaneMoveTimer,&QTimer::timeout,this,&GameWindow::PlaneMove);
}

GameWindow::~GameWindow()
{
    delete ui;
}

void GameWindow::initScene()
{
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);
    setWindowTitle(GAME_TITLE);
    setWindowIcon(QIcon(":/picture/images/me1.png"));
    m_Timer.setInterval(GAME_RATE);
}

void GameWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_W:
    case Qt::Key_S:
    case Qt::Key_A:
    case Qt::Key_D:
    mKeyList.append(event->key());
    break;
    }
}

void GameWindow::keyReleaseEvent(QKeyEvent *event)
{
    if(mKeyList.contains(event->key()))
    {
        mKeyList.removeOne(event->key());
    }
}

void GameWindow::PlaneMove()
{
    for(int keycode : mKeyList)
    {
        switch(keycode)
        {
        case Qt::Key_W: m_plane.setPosition(m_plane.m_x,m_plane.m_y-5);break;
        case Qt::Key_S: m_plane.setPosition(m_plane.m_x,m_plane.m_y+5);break;
        case Qt::Key_A: m_plane.setPosition(m_plane.m_x-5,m_plane.m_y);break;
        case Qt::Key_D: m_plane.setPosition(m_plane.m_x+5,m_plane.m_y);break;
        }
    }
}

void GameWindow::playGame()
{
    m_Timer.start();
    connect(&m_Timer,&QTimer::timeout,[=](){
        updatePosition();
        update();
    });
}

void GameWindow::updatePosition()
{
    m_map.mapPosition();
    m_plane.shoot();
    for(int i=0;i<BULLET_NUM;i++)
    {
        if(m_plane.m_bullet[i].m_free==false)
        {
            m_plane.m_bullet[i].updatePosition();
        }
    }
}

void GameWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawPixmap(0,m_map.m_map1_posY,m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY,m_map.m_map2);
    painter.drawPixmap(m_plane.m_x,m_plane.m_y,m_plane.m_plane);
    for(int i=0;i<BULLET_NUM;i++)
    {
        if(m_plane.m_bullet[i].m_free==false)
        {
            painter.drawPixmap(m_plane.m_bullet[i].m_x,m_plane.m_bullet[i].m_y,m_plane.m_bullet[i].m_bullet);
        }
    }
}

